package com.wanmait.movie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wanmait.movie.common.HttpCode;
import com.wanmait.movie.constant.UserContsant;
import com.wanmait.movie.entity.Admin;
import com.wanmait.movie.entity.request.manage.ManageLoginRequest;
import com.wanmait.movie.mapper.AdminMapper;
import com.wanmait.movie.service.ManageService;
import com.wanmait.movie.util.AjaxResult;
import com.wanmait.movie.util.JWTUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: ManageServiceImpl
 * Package: com.wanmait.movie.service.impl
 * Description:
 *
 * @Author Fengxd
 * @Create 2023/12/5 15:48
 * @Version 1.0
 */
@Service
public class ManageServiceImpl extends ServiceImpl<AdminMapper, Admin> implements ManageService {
    @Resource
    private AdminMapper adminMapper;
    @Value("60")
    Integer keepAlive;
    @Override
    public AjaxResult login(ManageLoginRequest manageLoginRequest, HttpServletRequest request) {
        String manageName = manageLoginRequest.getManageName();
        String password = manageLoginRequest.getPassword();
        // region 参数不能为空
        if (!StringUtils.hasLength(manageName)){
            return AjaxResult.error(HttpCode.PARAMETER_ERROR.getCode(),"账号为空");
        }
        if (!StringUtils.hasLength(password)){
            return AjaxResult.error(HttpCode.PARAMETER_ERROR.getCode(),"密码为空");
        }
        // endregion
        // region 管理员登录
        LambdaQueryWrapper<Admin> adminLoginQueryWrapper = new LambdaQueryWrapper<>();
        adminLoginQueryWrapper.eq(Admin::getAdminName,manageName);
        adminLoginQueryWrapper.eq(Admin::getPassword,password);
        Admin admin = adminMapper.selectOne(adminLoginQueryWrapper);
        if (admin == null){
            return AjaxResult.error(HttpCode.LOGIN_FAILED.getCode(), HttpCode.LOGIN_FAILED.getMsg());
        }
        String pass = admin.getPassword();
        // 隐藏密码
        admin.setPassword(null);
        // 记录登录状态
//        request.getSession().setAttribute("admin",admin);
        // 载荷
        Map<String,String> claims = new HashMap<>();
        claims.put("id",admin.getId().toString());
        claims.put("roles","admin");
        // 生成token
        String token = JWTUtils.createToken(admin.getId().toString(), keepAlive, pass, claims);
        return AjaxResult.success("登录成功",admin).put("token",token);
        // endregion
    }
}
